//
//  BlockWithInstanceVar.m
//  block
//
//  Created by Mac on 16/3/19.
//  Copyright © 2016年 Mac. All rights reserved.
//

#import "BlockWithInstanceVar.h"
@implementation BlockWithInstanceVar

/*
 在block中，我们可以直接访问和修改不带__block修饰符的成员变量，包括基本类型和对象类型的成员变量(包括修改对象成员变量的属性值)。
 在block后，修改效果在成员变量的作用域下均有效。
 
 ** 其实__block修饰符只能用于修饰自动变量
 */

- (void)createBlock {
    _personInstance = [[Person alloc] initWithName:@"apple"];
    _intInstance = 1;
    //访问成员变量
    [self usingBlockWithAccessInstance:^{
        NSLog(@"%@", self.personInstance.name); ///apple
        NSLog(@"%d", self.intInstance); //1
    }];
    
    //修改成员变量
    [self usingBlockWithModifyInstance:^{
        self.personInstance = [[Person alloc] initWithName:@"banana"]; //banana
        self.intInstance = 2; //2
        NSLog(@"personInstance's name in block = %@", self.personInstance.name);
        NSLog(@"intInstanc's name in block = %d", self.intInstance);
    }];
    NSLog(@"personInstance's name after block = %@", self.personInstance.name);
    NSLog(@"intInstanc's name after block = %d", self.intInstance);
    
    //修改成员变量的属性
    [self usingBlockWithModifyInstance:^{
        self.personInstance.name = @"cat";
        NSLog(@"modify instance's property, personInstance's name in block = %@",self.personInstance.name); //cat
    }];
    NSLog(@"modify instance's property, personInstance's name after block = %@",self.personInstance.name); //cat
}

- (void)usingBlockWithAccessInstance:(void(^)())block {
    block();
}

- (void)usingBlockWithModifyInstance:(void(^)())block {
    block();
}
@end
